import { Button, message, Table } from 'antd';
import React from 'react';
import { connect } from 'umi';
import SearchProduct from './SearchProduct';

const currControl = 'Edu_Product';
class ViewPage extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      loading: false,
      pageIndex: 1,
      pageSize: 10,
      dataSource: [],
      totalCount: 0,
      cascaderOption: [],
      selectedRowKeys: [],
      selectedRowData: [],
    };
  }
  componentDidMount() {
    this.getProductList();
    this.fetchCategory();
  }
  // 课程list
  getProductList = () => {
    const { params, pageIndex, pageSize } = this.state;
    this.props
      .dispatch({
        type: 'Abp/getList',
        payload: {
          SkipCount: (pageIndex - 1) * pageSize,
          MaxResultCount: pageSize,
          ...params,
        },
        control: currControl,
      })
      .then(() => {
        var resp = this.props.response;
        if (resp && resp.result) {
          this.setState({
            dataSource: resp.result.items,
            loading: false,
            totalCount: resp.result.totalCount,
          });
        }
      });
  };
  //分类
  fetchCategory = () => {
    this.props
      .dispatch({
        type: 'Category/getTreeData',
        payload: { layout: 'product' },
      })
      .then(() => {
        this.setState({ cascaderOption: this.props.Category.response.result });
      });
  };
  /**
   * @param values 搜索信息
   */
  handleSearch = (values: any) => {
    const { title, categoryId } = values;
    this.setState(
      {
        params: { title, categoryId },
        loading: true,
      },
      this.getProductList,
    );
  };
  //选择课程
  onSelectChange = (selectedRowKeys: any, values: any) => {
    if (this.props.onSelectChange) {
      this.props.onSelectChange(values);
    }
    this.setState({ selectedRowKeys, selectedRowData: values });
  };
  //添加产品
  handleAdd = () => {
    const { selectedRowData } = this.state;
    let product = this.props.id;
    var params: any = [];

    if (this.props.editStatus == 'product') {
      if (selectedRowData.length < 1) {
        message.warning('请至少选择一项！');
      } else {
        selectedRowData.forEach((item: any) => {
          var obj = {
            title: item.title,
            isTop: false,
            isRec: false,
            sortNum: '0',
            //productId给此产品添加课程
            //relationId课程id
            productId: product,
            relationId: item.id,
          };
          params.push(obj);
        });
        this.props
          .dispatch({
            type: 'Abp/createCourse',
            payload: params,
          })
          .then(() => {
            const resp = this.props.response;
            if (resp.success == true) {
              message.success('添加成功！');
              this.props.getExpandList(product);
            } else {
              message.error('添加失败，请重试！');
            }
          });
      }
    }
    if (this.props.editStatus == 'relation') {
      if (this.props.clickFun) {
        if (selectedRowData.length > 0) {
          this.props.clickFun(selectedRowData);
          message.success('添加成功！');
        } else {
          message.warning('至少选择一个产品!');
        }
      }
    }
  };
  render() {
    const { cascaderOption, loading, dataSource, selectedRowKeys, totalCount, pageSize } =
      this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    const columns = [
      {
        title: '产品名称',
        dataIndex: 'title',
        width: 130,
        ellipsis: true,
      },
      //   {
      //     title: '分类',
      //     width: 80,
      //     dataIndex: 'categoryId',
      //     ellipsis: true,
      //   },
    ];
    return (
      <>
        <SearchProduct onSearch={this.handleSearch} treeData={cascaderOption}>
          <Button danger onClick={this.handleAdd} style={{ marginLeft: 12 }}>
            添加
          </Button>
        </SearchProduct>
        <Table
          rowKey="id"
          loading={loading}
          rowSelection={rowSelection}
          columns={columns}
          dataSource={dataSource}
          scroll={{ y: 500 }}
          pagination={{
            onChange: (page, pageSize) => {
              this.setState({ pageIndex: page, pageSize }, () => {
                this.getProductList();
              });
            },

            pageSize: pageSize,
            pageSizeOptions: ['10', '50', '100', '5000'],
            total: totalCount,
          }}
        />
      </>
    );
  }
}

export default connect(({ Abp, Category }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
  Category,
}))(ViewPage);
